import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

const String h5JS2FlutterByChannel = '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>通过channel向flutter传递参数</title>
</head>
<body>
    <button id="btn">传递参数</button>
    <script type="text/javascript">
      var btn = document.getElementById('btn');
      btn.addEventListener('click', function() {
          hiPop.postMessage("Hi Pop message");
      });
    </script>
</body>
</html>
''';

class Js2flutterByChannel extends StatefulWidget {
  const Js2flutterByChannel({super.key});

  @override
  State<Js2flutterByChannel> createState() => _Js2flutterByChannelState();
}

class _Js2flutterByChannelState extends State<Js2flutterByChannel> {
  late WebViewController controller;

  get _loadBtn => FilledButton(
    onPressed: () {
      controller.loadHtmlString(h5JS2FlutterByChannel);
    },
    child: Text('加载H5', style: TextStyle(color: Colors.white)),
  );

  @override
  void initState() {
    super.initState();
    controller = WebViewController()
      // 开启JS执行
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..addJavaScriptChannel(
        'hiPop',
        onMessageReceived: (message) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(SnackBar(content: Text(message.message)));
        },
      );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('JS向flutter传递数据-通过channel方式'),
        actions: [_loadBtn],
      ),
      body: WebViewWidget(controller: controller),
    );
  }
}
